package com.qianseit.westore.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.DoActivity;
import com.qianseit.westore.Run;
import com.qianseit.westore.TwoGoodsAdapter;
import com.qianseit.westore.activity.GoodsDetailFragment.AddCartTask;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonRequestBean.JsonRequestCallback;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.ui.CircleFlowIndicator;
import com.qianseit.westore.ui.CustomDialog;
import com.qianseit.westore.ui.FlowView;
import com.qianseit.westore.ui.pulltorefresh.lib.PullToRefreshBase.OnRefreshListener;
import com.qianseit.westore.ui.pulltorefresh.lib.PullToRefreshListView;
import com.qianseit.westore.util.Util;
import com.qianseit.westore.util.loader.VolleyImageLoader;
import com.beautymiracle.androidclient.R;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class GoodsListFragment extends BaseDoFragment {
	private static final int FILTER_LIST = 0;
	private static final int FILTER_SMALL_IMAGE = 1;
	private final int REQUEST_SEARCH = 0x1001;
	private final static int INTERVAL_AUTO_SNAP_FLOWVIEW = 5000;

	private int mFirstVisibleItem;

	private PullToRefreshListView mGoodsListView;
	private View mEmptyView2;

	private Resources mResources;
	private BaseAdapter mGoodsAdapter;
	// private ImageLoader mImageLoader;
	private VolleyImageLoader mVolleyImageLoader;
	private int mFilterType = FILTER_LIST;

	private ViewGroup mSortDefaultView;
	private TextView mSortDefaultTextView;
	private ViewGroup mSortHotView;
	private TextView mSortHotTextView;
	private ViewGroup mSortBuyCountView;
	private TextView mSortBuyCountTextView;
	private ViewGroup mSortPriceView;
	private TextView mSortPriceTextView;
	private LinearLayout mFilterLayout;// 筛选条件item选项
	private Button mComfirmBtn;
	private Button mResetBtn;

	private FlowView mTopAdsView;
	private Point mScreenSize;
	private View mAdsLayoutView;

	// 购物车
	private RelativeLayout mShoppingCarLayout;
	private FrameLayout mAnimationLayout;
	private TextView mShoppingCount;
	private ArrayList<JSONObject> mTopAdsArray = new ArrayList<JSONObject>();

	// 查询参数
	private String mCategoryId;
	private String mVitualCategoryId;
	private String mKeywords;
	private String mSortKey;
	private int mPageNum;
	private int mQuantity = 1;
	private DrawerLayout mDrawerLayout;
	private boolean isOpened;
	private TextView mSearchText;

	private String mLastFilter;

	private ArrayList<JSONObject> mGoodsList = new ArrayList<JSONObject>();
	// 把筛选需要的数据整理成mFilterList name(类别) filters(类别下的子类) type_id(请求参数)
	// index(被选中的子类)
	private ArrayList<JSONObject> mFilterList = new ArrayList<JSONObject>();
	private ArrayList<JSONObject> mSelectFilterList = new ArrayList<JSONObject>();
	private int mTotalResult = 1;
	private JsonTask mTask;

	public GoodsListFragment() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setTitle(R.string.actionbar_button_assort);
		mResources = mActivity.getResources();
		// mImageLoader = Run.getDefaultImageLoader(mActivity, mResources);
		mVolleyImageLoader = ((AgentApplication) mActivity.getApplication())
				.getImageLoader();
		mScreenSize = Run.getScreenSize(mActivity.getWindowManager());

		Intent data = mActivity.getIntent();
		mKeywords = data.getStringExtra(Run.EXTRA_KEYWORDS);
		mCategoryId = data.getStringExtra(Run.EXTRA_CLASS_ID);
		mVitualCategoryId = data.getStringExtra(Run.EXTRA_VITUAL_CATE);
		mActionBar.setTitle(data.getStringExtra(Run.EXTRA_TITLE));
		mActionBar.getRightSearchView().setVisibility(View.VISIBLE);
		mActionBar.getRightSearchView().setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
		if (Run.goodsCounts > 0) {
			mShoppingCount.setVisibility(View.VISIBLE);
			mShoppingCount.setText(String.valueOf(Run.goodsCounts));
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeMessages(0);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 清空图片内存
		// mImageLoader.clearCache();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_goods_list, null);
		mDrawerLayout = (DrawerLayout) rootView
				.findViewById(R.id.drawer_layout);
		mActionBar.getBackButton().setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (isOpened) {
							mDrawerLayout.closeDrawer(Gravity.RIGHT);
							return;
						}
						getActivity().finish();
					}
				});
		mDrawerLayout.setDrawerListener(new DrawerListener() {

			@Override
			public void onDrawerStateChanged(int arg0) {
			}

			@Override
			public void onDrawerSlide(View arg0, float arg1) {
			}

			@Override
			public void onDrawerOpened(View arg0) {
				isOpened = true;
			}

			@Override
			public void onDrawerClosed(View arg0) {
				isOpened = false;
			}
		});

		// search view
		View mainView = inflater.inflate(R.layout.fragment_main, null);
		View searchView = mainView.findViewById(R.id.fragment_main_search);
		((ViewGroup) searchView.getParent()).removeView(searchView);
		searchView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		searchView.setOnClickListener(this);
		mActionBar.setCustomTitleView(searchView);
		mSearchText = (TextView) searchView
				.findViewById(R.id.fragment_main_search_text);
		if (!TextUtils.isEmpty(mKeywords)) {
			mSearchText.setText(mKeywords);
		}

		// 排序
		mSortDefaultView = (ViewGroup) findViewById(R.id.goods_list_topbar_sort_default);
		mSortBuyCountView = (ViewGroup) findViewById(R.id.goods_list_topbar_sort_sales);
		mSortPriceView = (ViewGroup) findViewById(R.id.goods_list_topbar_sort_price);
		mSortHotView = (ViewGroup) findViewById(R.id.goods_list_topbar_sort_hot);
		mSortDefaultTextView = (TextView) mSortDefaultView.getChildAt(0);
		mSortHotTextView = (TextView) mSortHotView.getChildAt(0);
		mSortBuyCountTextView = (TextView) mSortBuyCountView.getChildAt(0);
		mSortPriceTextView = (TextView) mSortPriceView.getChildAt(0);
		mSortDefaultView.setOnClickListener(mSortClickListener);
		mSortBuyCountView.setOnClickListener(mSortClickListener);
		mSortPriceView.setOnClickListener(mSortClickListener);
		mSortHotView.setOnClickListener(mSortClickListener);
		mSortDefaultTextView.setSelected(true);

		// 筛选
		mFilterLayout = (LinearLayout) findViewById(R.id.fragment_filter_layout);
		mComfirmBtn = (Button) findViewById(R.id.fragment_filter_sure);
		mResetBtn = (Button) findViewById(R.id.fragment_filter_reset);
		mComfirmBtn.setOnClickListener(this);
		mResetBtn.setOnClickListener(this);

		mShoppingCarLayout = (RelativeLayout) findViewById(R.id.goods_list_shoppingcar);
		mShoppingCarLayout.setOnClickListener(this);
		mAnimationLayout = (FrameLayout) findViewById(R.id.goods_list_animation_layout);
		mShoppingCount = (TextView) findViewById(R.id.goods_list_shoppingcar_count);

		mActionBar.setShowRightButton(true);
		mActionBar.getRightButton().setOnClickListener(this);
		mActionBar.getRightButton().setText(R.string.small_picture);
		mActionBar.getRightButton().setCompoundDrawablesWithIntrinsicBounds(
				R.drawable.goods_list_filter_small, 0, 0, 0);

		mEmptyView2 = inflater
				.inflate(R.layout.pull_to_refresh_emptyview, null);
		mGoodsListView = (PullToRefreshListView) findViewById(R.id.goods_list_listview);
		mAdsLayoutView = findViewById(R.id.fragment_goods_list_top_adsview_layout);
		mTopAdsView = (FlowView) findViewById(R.id.fragment_goods_list_top_adsview);
		Run.removeFromSuperView(mAdsLayoutView);
		mAdsLayoutView.setLayoutParams(new AbsListView.LayoutParams(
				mAdsLayoutView.getLayoutParams()));
		mGoodsListView.getRefreshableView().addHeaderView(mAdsLayoutView);
		mGoodsAdapter = new GoodsListAdapter();
		mGoodsListView.getRefreshableView().setAdapter(mGoodsAdapter);
		mGoodsListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				loadNextPage(0);
				refreshAds();
				mAdsLayoutView.setVisibility(View.GONE);
			}

			@Override
			public void onRefreshMore() {
			}
		});
		mGoodsListView.getRefreshableView().setOnScrollListener(
				new OnScrollListener() {
					@Override
					public void onScrollStateChanged(AbsListView view,
							int scrollState) {
					}

					@Override
					public void onScroll(AbsListView view,
							int firstVisibleItem, int visibleItemCount,
							int totalItemCount) {
						mFirstVisibleItem = firstVisibleItem;
						if (totalItemCount < 5 || mTask == null
								|| mTask.isExcuting)
							return;

						// 滚动到倒数第五个时，自动加载下一页
						if (totalItemCount
								- (firstVisibleItem + visibleItemCount) <= 5)
							loadNextPage(mPageNum);
					}
				});

		// 加载第一页内容
		new JsonTask().execute(new GetFilterList());
		loadNextPage(mPageNum);
		refreshAds();
	}
	
	/**
	 * 获取广告
	 * @author chesonqin
	 * 2014-12-31
	 */
	private void refreshAds(){
		mTopAdsArray.clear();
		if (!TextUtils.isEmpty(mCategoryId) || !TextUtils.isEmpty(mVitualCategoryId)) {
			new JsonTask().execute(new GetTopAds());
		} else {
			new JsonTask().execute(new GetTopAds(true));
		}
	}

	// 加载下一页
	private void loadNextPage(int oldPageNum) {
		this.mPageNum = oldPageNum + 1;
		if (this.mPageNum == 1) {
			mGoodsList.clear();
			mGoodsAdapter.notifyDataSetChanged();
			mGoodsListView.setRefreshing();
			mTotalResult = 1;
		}

		if (mTotalResult > mGoodsList.size()) {
			mTask = new JsonTask();
			if (mSelectFilterList.size() > 0) {
				Run.excuteJsonTask(mTask, new GetGoodsByFilter());
			} else {
				mLastFilter = "";
				Run.excuteJsonTask(mTask, new TopLevelTask());
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (mActionBar.getRightButton() == v) {
			if (isOpened) {
				mDrawerLayout.closeDrawer(Gravity.RIGHT);
				return;
			}
			mFilterType = (mFilterType + 1) % 2;
			switch (mFilterType) {
			case FILTER_SMALL_IMAGE:
				mShoppingCarLayout.setVisibility(View.INVISIBLE);
				mActionBar.getRightButton()
						.setCompoundDrawablesWithIntrinsicBounds(
								R.drawable.goods_list_filter_list, 0, 0, 0);
				mActionBar.getRightButton().setText(R.string.list);
				mGoodsAdapter = new GoodsGridAdapter();
				mGoodsListView.getRefreshableView().setAdapter(mGoodsAdapter);
				break;
			default:
				mShoppingCarLayout.setVisibility(View.VISIBLE);
				mActionBar.getRightButton()
						.setCompoundDrawablesWithIntrinsicBounds(
								R.drawable.goods_list_filter_small, 0, 0, 0);
				mActionBar.getRightButton().setText(R.string.small_picture);
				mGoodsAdapter = new GoodsListAdapter();
				mGoodsListView.getRefreshableView().setAdapter(mGoodsAdapter);
				break;
			}
		} else if (R.id.fragment_main_search == v.getId()) {
			if (isOpened) {
				mDrawerLayout.closeDrawer(Gravity.RIGHT);
				return;
			}
			// if (TextUtils.isEmpty(mKeywords))
			// mActivity.finish();
			startActivityForResult(
					AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_SEARCH)
							.putExtra(Run.EXTRA_KEYWORDS, mKeywords)
							.putExtra(Run.EXTRA_METHOD, true), REQUEST_SEARCH);
		} else if (mActionBar.getRightSearchView() == v) {
			if (isOpened) {
				mDrawerLayout.closeDrawer(Gravity.RIGHT);
			} else {
				mDrawerLayout.openDrawer(Gravity.RIGHT);
			}
		} else if (mShoppingCarLayout == v) {
			startActivity(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_SHOPPING_CAR));
		} else if (mComfirmBtn == v) {
			mSelectFilterList.clear();
			for (int i = 0; i < mFilterLayout.getChildCount(); i++) {
				View view = mFilterLayout.getChildAt(i);
				TextView filter = (TextView) view
						.findViewById(R.id.item_filter_name_filter);
				if (filter.getTag() == null) {
					continue;
				}
				JSONObject obj = (JSONObject) filter.getTag();
				mSelectFilterList.add(obj);
				Log.i("", "------>>> :" + obj.toString());
			}
			String tempString = "";
			for (int i = 0; i < mSelectFilterList.size(); i++) {
				JSONObject obj = mSelectFilterList.get(i);
				tempString += (obj.optString("type_id") + "="
						+ obj.optString("index") + "-");
			}
			if (!mLastFilter.equals(tempString)) {
				loadNextPage(0);
			}

			mDrawerLayout.closeDrawers();
		} else if (mResetBtn == v) {
			for (int i = 0; i < mFilterLayout.getChildCount(); i++) {
				View view = mFilterLayout.getChildAt(i);
				TextView filter = (TextView) view
						.findViewById(R.id.item_filter_name_filter);
				filter.setTag(null);
				filter.setText("");
			}
		} else {
			super.onClick(v);
		}
	}

	private void openGoodsDetailPage(String goodsIID, String productID) {
		Intent intent = AgentActivity
				.intentForFragment(mActivity,
						AgentActivity.FRAGMENT_GOODS_DETAIL)
				.putExtra(Run.EXTRA_CLASS_ID, goodsIID)
				.putExtra(Run.EXTRA_PRODUCT_ID, productID);
		mActivity.startActivity(intent);
	}

	@SuppressLint("NewApi")
	private class GoodsListAdapter extends BaseAdapter implements
			OnClickListener {
		private LayoutInflater inflater;

		public GoodsListAdapter() {
			inflater = mActivity.getLayoutInflater();
		}

		@Override
		public int getCount() {
			return mGoodsList.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mGoodsList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				int layout = R.layout.fragment_goods_list_item_list;
				convertView = inflater.inflate(layout, null);
				convertView.setOnClickListener(this);
				convertView.findViewById(android.R.id.icon)
						.setDrawingCacheEnabled(true);
			}

			JSONObject all = getItem(position);
			if (all == null)
				return convertView;

			// 没有货品不显示购物车按钮
			View view = convertView.findViewById(R.id.add_buy_car);
			view.setOnClickListener(this);
			view.setTag(R.id.tag_first, position);
			try {
				JSONArray skus = new JSONArray(all.optString("skus"));
				view.setTag(R.id.tag_second, skus);
				if (skus == null || skus.length() <= 0) {
					view.setVisibility(View.GONE);
				} else {
					if (skus.optJSONObject(0).optBoolean("is_starbuy")) {
						view.setVisibility(View.GONE);
					} else {
						view.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			}

			// convertView.setTag(all.optString("iid"));
			convertView.setTag(all);
			fillupItemView(convertView, all, "small_url");

			return convertView;
		}

		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.add_buy_car) {
				if (v.getTag(R.id.tag_second) == null
						|| !(v.getTag(R.id.tag_second) instanceof JSONArray))
					return;
				// if (v.getTag() != null && !TextUtils.isEmpty((String)
				// v.getTag())){
				// int position = (Integer) v.getTag();
				// JSONObject all = getItem(position);
				JSONArray skus = (JSONArray) v.getTag(R.id.tag_second);
				if (skus.length() > 0) {
					JSONObject sku = skus.optJSONObject(0);
					String bn = sku.optString("sku_id");
					JsonTaskHandler newTask = new AddCartTask(
							(DoActivity) mActivity, mAddCarCallback, bn, 1,
							Run.EMPTY_STR);
					Run.excuteJsonTask(new JsonTask(), newTask);
				}
				Object tag = v.getTag(R.id.tag_first);
				if (tag != null) {
					int position = (Integer) tag;
					View view = mGoodsListView.getAdapterView().getChildAt(
							position - mFirstVisibleItem + 1);
					ImageView image = (ImageView) view
							.findViewById(android.R.id.icon);
					Bitmap bmp = image.getDrawingCache();
					ImageView img = new ImageView(getActivity());
					img.setLayoutParams(new FrameLayout.LayoutParams(bmp
							.getWidth(), bmp.getHeight()));
					img.setX(view.getX() + Util.dip2px(mActivity, 10));
					img.setY(view.getY() + Util.dip2px(mActivity, 10));
					img.setImageBitmap(bmp);
					mAnimationLayout.addView(img);

					setAnimation(img);
				}
			} else {
				if (v.getTag() != null) {
					JSONObject obj = (JSONObject) v.getTag();
					String goodsId = "";
					String product_id = "";
					JSONArray skus = obj.optJSONArray("skus");
					if (skus != null && skus.length() > 0) {
						if (!skus.optJSONObject(0).optBoolean("is_starbuy")) {
							goodsId = obj.optString("iid");
						} else {
							product_id = skus.optJSONObject(0).optString(
									"sku_id");
						}
					}
					openGoodsDetailPage(goodsId, product_id);
				}
			}
		}

	}

	private void setAnimation(View view) {
		AnimationSet set = new AnimationSet(true);
		TranslateAnimation t = new TranslateAnimation(0, Util.dip2px(mActivity,
				327), 0, Util.dip2px(mActivity, 493) - view.getY() * 0.1f);
		t.setDuration(500);
		ScaleAnimation sa = new ScaleAnimation(1.0f, 0.1f, 1.0f, 0.1f);
		sa.setDuration(500);
		set.addAnimation(sa);
		set.addAnimation(t);
		view.startAnimation(set);
		set.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				mAnimationLayout.removeAllViews();
			}
		});
	}

	/* 加入购物车成功 */
	private JsonRequestCallback mAddCarCallback = new JsonRequestCallback() {
		@Override
		public void task_response(String jsonStr) {
			Run.alert(mActivity, R.string.add_to_shoping_car_success);
			Run.excuteJsonTask(new JsonTask(), new GetCarCountTask());
			new JsonTask().execute(new GetCarCountTask());
		}
	};

	private class GetCarCountTask implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject data = all.optJSONObject("data");
					JSONObject object = data.optJSONObject("object");
					JSONArray goods = object.optJSONArray("goods");
					int size = (goods == null) ? 0 : goods.length();
					int count = 0;
					for (int i = 0; i < size; i++) {
						count += goods.getJSONObject(i).optInt("quantity");
					}
					Run.goodsCounts = count;
					if (count > 0) {
						mShoppingCount.setVisibility(View.VISIBLE);
						mShoppingCount.setText(String.valueOf(Run.goodsCounts));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			return new JsonRequestBean(Run.API_URL, "mobileapi.cart.get_list");
		}
	}

	private class GetFilterList implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject data = all.optJSONObject("data");
					JSONArray props = data.optJSONArray("props");
					JSONObject newObj = null;
					JSONObject filter = null;
					String type_id = "";
					for (int i = 0; props != null && i < props.length(); i++) {
						JSONObject obj = props.getJSONObject(i);
						newObj = new JSONObject();
						newObj.put("name", obj.optString("name"));
						newObj.put("filters", obj.optJSONObject("options"));
						type_id = "p_" + obj.getString("goods_p");
						newObj.put("type_id", type_id);
						mFilterList.add(newObj);
					}
					JSONObject spec = data.optJSONObject("spec");
					if (spec != null) {
						Iterator<String> keys = spec.keys();
						while (keys.hasNext()) {
							String key = keys.next();
							JSONObject obj = spec.optJSONObject(key);
							JSONObject specValue = obj
									.optJSONObject("spec_value");
							Iterator<String> keysInner = specValue.keys();
							type_id = "s_" + key;
							while (keysInner.hasNext()) {
								filter = new JSONObject();
								String keyInner = keysInner.next();
								JSONObject objInner = specValue
										.getJSONObject(keyInner);
								filter.put(keyInner,
										objInner.optString("spec_value"));
							}
							newObj = new JSONObject();
							String name = obj.optString("name");
							newObj.put("name", name);
							newObj.put("filters", filter);
							newObj.put("type_id", type_id);
							mFilterList.add(newObj);
						}
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				for (int i = 0, c = mFilterList.size(); i < c; i++) {
					View itemView = makeFilterItem(mFilterList.get(i));
					mFilterLayout.addView(itemView);
					if (i == c - 1) {
						itemView.findViewById(R.id.item_filter_divider)
								.setVisibility(View.GONE);
					}
				}

				mFilterLayout.setVisibility(mFilterList.isEmpty() ? View.GONE
						: View.VISIBLE);
				findViewById(R.id.fragment_filter_noresult).setVisibility(
						!mFilterList.isEmpty() ? View.GONE : View.VISIBLE);
			}
		}

		@Override
		public JsonRequestBean task_request() {
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.goods.get_screen");

			if (!TextUtils.isEmpty(mKeywords)) {
				req.addParams("search_keywords", mKeywords);
			} else if (!TextUtils.isEmpty(mCategoryId)) {
				req.addParams("cat_id", mCategoryId);
			}
			return req;
		}

	}

	private class GetGoodsByFilter implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {

			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject child = all.optJSONObject("data");
					mTotalResult = child.optInt("total_results");
					if (child != null
							&& !TextUtils.isEmpty(child.optString("items"))) {
						parseGoodsList(new JSONObject(child.optString("items")));
						mGoodsAdapter.notifyDataSetChanged();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				mGoodsListView.onRefreshComplete();
				// 使用未搜索到商品的文字提示view
				ListView lv = mGoodsListView.getRefreshableView();
				if (mGoodsList.isEmpty()) {
					if (lv.getHeaderViewsCount() <= 0) {
						lv.setAdapter(null);
						lv.addHeaderView(mEmptyView2);
						lv.setAdapter(mGoodsAdapter);
					}
				} else {
					lv.removeHeaderView(mEmptyView2);
				}
			}

		}

		@Override
		public JsonRequestBean task_request() {
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.goods.filter_get_goods");
			mLastFilter = "";
			for (int i = 0; i < mSelectFilterList.size(); i++) {
				JSONObject obj = mSelectFilterList.get(i);
				req.addParams(obj.optString("type_id"), obj.optString("index"));
				mLastFilter += (obj.optString("type_id") + "="
						+ obj.optString("index") + "-");
			}
			req.addParams("page_no", String.valueOf(mPageNum));
			if (!TextUtils.isEmpty(mCategoryId))
				req.addParams("cat_id", mCategoryId);
			if (!TextUtils.isEmpty(mKeywords))
				req.addParams("search_keyword", mKeywords);
			if (!TextUtils.isEmpty(mSortKey))
				req.addParams("orderby", mSortKey);
			if (!TextUtils.isEmpty(mVitualCategoryId))
				req.addParams("virtual_cat_id", mVitualCategoryId);
			return req;
		}

	}

	private View makeFilterItem(JSONObject data) {
		View view = LayoutInflater.from(mActivity).inflate(
				R.layout.item_filter_view, null);
		TextView filterName = (TextView) view
				.findViewById(R.id.item_filter_name);
		filterName.setText(data.optString("name"));
		// TextView item_filter_name_filter = (TextView)
		// view.findViewById(R.id.item_filter_name);
		view.setTag(data);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				showSelectItemDialog(view);
			}
		});
		return view;
	}

	private void showSelectItemDialog(final View v) {
		JSONObject obj = null;
		int indexTemp = 0;
		for (int i = 0; i < mFilterLayout.getChildCount(); i++) {
			if (mFilterLayout.getChildAt(i) == v) {
				obj = mFilterList.get(i);
				indexTemp = i;
				break;
			}
		}
		final int index = indexTemp;
		if (obj == null) {
			return;
		}
		final List<String> list = new ArrayList<String>();
		JSONObject filters = obj.optJSONObject("filters");
		Iterator<String> keys = filters.keys();
		List<String> listKey = new ArrayList<String>();
		while (keys.hasNext()) {
			String key = keys.next();
			listKey.add(key);
		}
		Collections.sort(listKey);
		for (int i = 0; i < listKey.size(); i++) {
			list.add(filters.optString(listKey.get(i)));
		}
		final CustomDialog mDialog = new CustomDialog(mActivity);
		mDialog.setTitle(obj.optString("name"));
		mDialog.setSingleChoiceItems(new FilterAdapter(list), -1,
				new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						TextView tv = ((TextView) v
								.findViewById(R.id.item_filter_name_filter));
						tv.setText(list.get(position));
						JSONObject data = mFilterList.get(index);
						JSONObject filters = data.optJSONObject("filters");
						Iterator<String> keys = filters.keys();
						while (keys.hasNext()) {
							String key = keys.next();
							if (filters.optString(key).equals(
									list.get(position))) {
								try {
									data.put("index", key);
								} catch (JSONException e) {
									e.printStackTrace();
								}
								break;
							}
						}
						tv.setTag(data);
						mDialog.dismiss();
					}
				}).setCancelable(true).setCanceledOnTouchOutside(true).show();
	}

	private class FilterAdapter extends BaseAdapter {

		List<String> items = null;

		public FilterAdapter(List<String> items) {
			this.items = items;
		}

		@Override
		public int getCount() {
			if (items != null) {
				return items.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			if (convertView == null) {
				convertView = mActivity.getLayoutInflater().inflate(
						android.R.layout.simple_list_item_1, null);
				TextView tv = ((TextView) convertView
						.findViewById(android.R.id.text1));
				tv.setTextColor(mActivity.getResources().getColor(
						R.color.westore_primary_textcolor));
				tv.setTextSize(16);
			}

			((TextView) convertView.findViewById(android.R.id.text1))
					.setText(items.get(position));
			return convertView;
		}

	}

	private class FlowAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mTopAdsArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mTopAdsArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				ImageView view = new ImageView(mActivity);
				view.setLayoutParams(new AbsListView.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
				view.setScaleType(ScaleType.CENTER_CROP);
				view.setOnClickListener(mAdViewClickListener);
				convertView = view;
			}

			JSONObject topAdsObject = getItem(position);
			// Uri imageUri = Uri.parse(topAdsObject.optString("ad_img"));
			convertView.setTag(R.id.tag_object, topAdsObject);
			// convertView.setTag(imageUri);
			// mImageLoader.showImage((ImageView) convertView, imageUri);
			((ImageView) convertView).setImageBitmap(null);
			mVolleyImageLoader.showImage((ImageView) convertView,
					topAdsObject.optString("ad_img"));
			return convertView;
		}

	}

	private class GoodsGridAdapter extends TwoGoodsAdapter {

		public GoodsGridAdapter() {
			super(GoodsListFragment.this.mActivity,
					GoodsListFragment.this.mVolleyImageLoader,
					GoodsListFragment.this.mGoodsList);
		}

		@Override
		public void onClick(View v) {
			if (v.getTag(R.id.tag_first) != null) {
				JSONObject obj = (JSONObject) v.getTag(R.id.tag_first);
				String goodsId = "";
				String product_id = "";
				JSONArray skus = obj.optJSONArray("skus");
				if (skus != null && skus.length() > 0) {
					if (!skus.optJSONObject(0).optBoolean("is_starbuy")) {
						goodsId = obj.optString("iid");
					} else {
						product_id = skus.optJSONObject(0).optString("sku_id");
					}
				}
				openGoodsDetailPage(goodsId, product_id);
			}
		}

		/**
		 * 填充列表信息
		 * 
		 * @param convertView
		 * @param all
		 * @param key
		 */
		public void fillupItemView(View convertView, JSONObject all, String key) {
			GoodsListFragment.this.fillupItemView(convertView, all, key);
		}
	}

	/**
	 * 填充列表信息
	 * 
	 * @param convertView
	 * @param all
	 * @param key
	 */
	private void fillupItemView(View convertView, JSONObject all, String key) {
		((TextView) convertView.findViewById(android.R.id.title)).setText(all
				.optString("title"));
		convertView.setTag(R.id.tag_first, all);
		// 购买说明
		View summary = convertView.findViewById(android.R.id.summary);
		if (summary != null)
			((TextView) summary).setText(all.optString("brief"));

		// 月销量
		View sales = convertView.findViewById(R.id.goods_list_item_list_sales);
		if (sales != null)
			((TextView) sales).setText(mActivity.getString(
					R.string.goods_list_sales, all.optString("buy_count")));

		((TextView) convertView.findViewById(android.R.id.text1)).setText(Run
				.buildString("￥", all.optString("price")));
		TextView tv2 = (TextView) convertView.findViewById(android.R.id.text2);
		tv2.setText(Run.buildString("￥", all.optString("market_price")));
		tv2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

		try {
			ImageView iconView = (ImageView) convertView
					.findViewById(android.R.id.icon);
			JSONArray imgJson = new JSONArray(all.optString("item_imgs"));
			JSONObject child = null;
			String imageUrl = "";
			if (imgJson != null && imgJson.length() > 0) {
				child = imgJson.getJSONObject(0);
				imageUrl = child.optString("thisuasm_url");
			}
			// String imageUrl = all.optString("default_img_url");
			if (TextUtils.isEmpty(imageUrl)) {
				imageUrl = all.optString("default_img_url");
			}
			// Uri imageUri = Uri.parse(imageUrl);
			// iconView.setTag(imageUri);
			// mImageLoader.showImage(iconView, imageUri);
			iconView.setImageBitmap(null);
			mVolleyImageLoader.showImage(iconView, imageUrl);
		} catch (Exception e) {
		}
	}

	/**
	 * 解析
	 * 
	 * @param all
	 */
	private void parseGoodsList(JSONObject top) {
		JSONArray all = top.optJSONArray("item");
		if (all != null && all.length() > 0) {
			for (int i = 0, c = all.length(); i < c; i++) {
				try {
					JSONObject child = all.getJSONObject(i);
					mGoodsList.add(child);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	private class TopLevelTask implements JsonTaskHandler {
		@Override
		public JsonRequestBean task_request() {
			JsonRequestBean bean = new JsonRequestBean(Run.API_URL,
					"mobileapi.goods.get_all_list").addParams("page_no",
					String.valueOf(mPageNum));
			if (!TextUtils.isEmpty(mCategoryId))
				bean.addParams("cat_id", mCategoryId);
			if (!TextUtils.isEmpty(mKeywords))
				bean.addParams("search_keyword", mKeywords);
			if (!TextUtils.isEmpty(mSortKey))
				bean.addParams("orderby", mSortKey);
			if (!TextUtils.isEmpty(mVitualCategoryId))
				bean.addParams("virtual_cat_id", mVitualCategoryId);
			bean.addParams("son_object", "json");
			return bean;
		}

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject child = all.optJSONObject("data");
					mTotalResult = child.optInt("total_results");
					if (child != null
							&& !TextUtils.isEmpty(child.optString("items"))) {
						parseGoodsList(new JSONObject(child.optString("items")));
						mGoodsAdapter.notifyDataSetChanged();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				mGoodsListView.onRefreshComplete();
				// 使用未搜索到商品的文字提示view
				ListView lv = mGoodsListView.getRefreshableView();
				if (mGoodsList.isEmpty()) {
					if (lv.getHeaderViewsCount() <= 0) {
						lv.setAdapter(null);
						lv.addHeaderView(mEmptyView2);
						lv.setAdapter(mGoodsAdapter);
					}
				} else {
					lv.removeHeaderView(mEmptyView2);
				}
			}
		}
	}

	private OnClickListener mSortClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			mSortDefaultTextView.setSelected(false);
			mSortBuyCountTextView.setSelected(false);
			mSortPriceTextView.setSelected(false);
			mSortHotTextView.setSelected(false);
			if (v == mSortDefaultView) {
				mSortDefaultTextView.setSelected(true);
				mSortKey = null;
			} else if (v == mSortHotView) {
				mSortHotTextView.setSelected(true);
				mSortKey = "view_count";
			} else if (v == mSortBuyCountView) {
				mSortBuyCountTextView.setSelected(true);
				if (TextUtils.equals("buy_count desc", mSortKey)) {
					mSortBuyCountTextView
							.setCompoundDrawablesWithIntrinsicBounds(0, 0,
									R.drawable.goods_list_topbar_arrow_asc, 0);
					mSortKey = "buy_count asc";
				} else {
					mSortBuyCountTextView
							.setCompoundDrawablesWithIntrinsicBounds(0, 0,
									R.drawable.goods_list_topbar_arrow, 0);
					mSortKey = "buy_count desc";
				}
			} else if (v == mSortPriceView) {
				mSortPriceTextView.setSelected(true);
				if (TextUtils.equals(mSortKey, "price asc")) {
					mSortPriceTextView.setCompoundDrawablesWithIntrinsicBounds(
							0, 0, R.drawable.goods_list_topbar_arrow, 0);
					mSortKey = "price desc";
				} else {
					mSortPriceTextView.setCompoundDrawablesWithIntrinsicBounds(
							0, 0, R.drawable.goods_list_topbar_arrow_asc, 0);
					mSortKey = "price asc";
				}
			}
			loadNextPage(0);
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == 0x1001) {
			mKeywords = data.getStringExtra(Run.EXTRA_KEYWORDS);
			mVitualCategoryId = "";
			mSortKey = "";
			mCategoryId = "";
			mSearchText.setText(mKeywords);
			loadNextPage(0);
		}
	};

	private void reloadAdsView() {
		if (mTopAdsArray != null && mTopAdsArray.size() > 0) {
			mAdsLayoutView.setVisibility(View.VISIBLE);
			CircleFlowIndicator mTopAdsIndicator = (CircleFlowIndicator) rootView
					.findViewById(R.id.fragment_goods_list_top_adsview_indicator);
			mTopAdsIndicator.setVisibility(View.VISIBLE);
			mTopAdsView.setAdapter(new FlowAdapter());
			mTopAdsView.setFlowIndicator(mTopAdsIndicator);
			mTopAdsIndicator.setViewFlow(mTopAdsView);
			try {
				JSONObject topAdsObject = mTopAdsArray.get(0);

				// 根据屏幕和图片大小调整显示尺寸
				int width = topAdsObject.optInt("ad_img_w");
				int height = topAdsObject.optInt("ad_img_h");
				int viewHeight = mScreenSize.x * height / width;
				LayoutParams params = mTopAdsView.getLayoutParams();
				params.height = viewHeight;
				mTopAdsView.setLayoutParams(params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (mTopAdsView.getViewsCount() > 1) {
				int count = mTopAdsView.getViewsCount();
				int curScreen = mTopAdsView.getSelectedItemPosition();
				if (curScreen >= (count - 1))
					mTopAdsView.smoothScrollToScreen(0);
				else
					mTopAdsView.smoothScrollToScreen(curScreen + 1);
			}
			mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
		};
	};

	private OnClickListener mAdViewClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (v.getTag(R.id.tag_object) != null) {
				JSONObject data = (JSONObject) v.getTag(R.id.tag_object);
				String urlType = data.optString("url_type");
				if ("goods".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_GOODS_DETAIL).putExtra(
							Run.EXTRA_CLASS_ID, data.optString("ad_url")));
				} else if ("article".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_ARTICLE_READER).putExtra(
							Run.EXTRA_ARTICLE_ID, data.optString("ad_url")));
				} else if ("virtual_cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_VITUAL_CATE,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				} else if ("cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_CLASS_ID,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				}
			}
		}
	};

	private class GetTopAds implements JsonTaskHandler {
		
		private boolean isGetComm_ad = false;
		
		public GetTopAds(boolean isGetComm_ad){
			this.isGetComm_ad = isGetComm_ad;
		}
		
		public GetTopAds(){}
		
		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONArray list = all.getJSONArray("data");
					if (list != null && list.length() > 0) {
						list = list.getJSONObject(0).getJSONArray("items");
						int count = (list != null) ? list.length() : 0;
						for (int i = 0; i < count; i++) {
							mTopAdsArray.add((JSONObject) list.get(i));
						}
					}
					if (isGetComm_ad) {
						reloadAdsView();
					} else {
						new JsonTask().execute(new GetTopAds(true));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.salesgoods.get_sales_ads");
			if (isGetComm_ad) {
				req.addParams("ad_type", "common");
				req.addParams("ad_type_id", "comm_list_ad");
			} else {
				if (!TextUtils.isEmpty(mCategoryId)) {
					req.addParams("ad_type", "cat");
					req.addParams("ad_type_id", mCategoryId);
				} else if(!TextUtils.isEmpty(mVitualCategoryId)){
					req.addParams("ad_type", "virtual_cat");
					req.addParams("ad_type_id", mVitualCategoryId);
				}
			}
//			if (!TextUtils.isEmpty(mCategoryId)) {
//				req.addParams("ad_type", "cat");
//				req.addParams("ad_type_id", mCategoryId);
//			} else if(!TextUtils.isEmpty(mVitualCategoryId)){
//				req.addParams("ad_type", "virtual_cat");
//				req.addParams("ad_type_id", mVitualCategoryId);
//			} else {
//				req.addParams("ad_type", "common");
//				req.addParams("ad_type_id", "comm_list_ad");
//			}
			//req.addParams("ad_position", "2");
		 return req;
		}
	}
	
}
